<?php

namespace app\common\model;

use think\Model;

class Admin extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 重置用户密码
     * @author baiyouwen
     */
    public function resetPassword($uid, $NewPassword)
    {
        $passwd = $this->encryptPassword($NewPassword);
        $ret = $this->where(['id' => $uid])->update(['password' => $passwd]);
        return $ret;
    }

    // 密码加密
    protected function encryptPassword($password, $salt = '', $encrypt = 'md5')
    {
        return $encrypt($password . $salt);
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public static function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public static function getStatusText($key='')
    {
        $statusArr = ['normal'=>'正常', 'hidden'=>'隐藏'];
        return $statusArr[$key];
    }

    /**
     * 用户列表
     * @param $data
     * @return array
     */
    public static function getList($data)
    {
        $where = '1=1';
        $order = 'a.id desc';
        $page  = isset($data['page']) && !empty($data['page']) ? intval($data['page']) : 1;
        $limit  = isset($data['limit']) && !empty($data['limit']) ? intval($data['limit']) : 10;
        $start = ($page-1)*$limit;
        $field = "a.id, a.username, a.email, a.mobile, a.avatar, a.money, a.joinip, a.status, a.openid, a.createtime, a.logintime";

        if(isset($data['mobile']) && !empty($data['mobile'])) $where.=" and a.mobile like '%{$data['mobile']}%'";

        $list = db('user')
            ->alias('a')
            ->where($where)
            ->order($order)
            ->limit($start, $limit)
            ->field($field)
            ->select();
        if(!empty($list))
        {
            foreach ($list as &$v)
            {
                $v['statusText'] = self::getStatusText($v['status']);
                $v['createtimeText'] = isset($v['createtime']) && !empty($v['createtime']) ? date('Y-m-d H:i:s', $v['createtime']) : '';
                $v['logintimeText'] = isset($v['logintime']) && !empty($v['logintime']) ? date('Y-m-d H:i:s', $v['logintime']) : '';
            }
            unset($v);
        }

        $total = db('user')
            ->alias('a')
            ->where($where)
            ->count();

        return [
            'list' => $list,
            'total' => $total,
        ];

    }

}
